package ldh.im.web.controller;

 /**
 * @author: ldh
 * @date: 2021-06-06 10:17:43
 */

import ldh.common.json.JsonViewFactory;
import ldh.common.mybatis.ValuedEnum;
import ldh.im.web.constant.AuthorityStatus;
import ldh.im.web.constant.ModuleStatus;
import ldh.im.web.constant.RoleStatus;
import ldh.im.web.constant.UserStatus;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;

@Controller
@RequestMapping("/common")
public class CommonController {

    @Value("${im.uploadDir}")
    private String uploadDir;
    @Value("${im.staticPath}")
    private String staticPath;

    private Map<String, Class> enumMap = new HashMap<>();
    {
        enumMap.put("UserStatus", UserStatus.class);
        enumMap.put("RoleStatus", RoleStatus.class);
        enumMap.put("ModuleStatus", ModuleStatus.class);
        enumMap.put("AuthorityStatus", AuthorityStatus.class);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/all/json/{enumName}")
    @ResponseBody
    public String listJson(@PathVariable("enumName") String enumName, Model model) throws Exception{
        Class clazz = enumMap.get(enumName);
        Method method = MethodUtils.getAccessibleMethod(clazz, "values", new Class[]{});
        ValuedEnum[] ves = (ValuedEnum[]) method.invoke(null, new Object[]{});
        List<Map<String, Object>> list = new ArrayList<>();
        for (ValuedEnum ve : ves) {
            Map<String, Object> map = new HashMap<>();
            map.put("value", ve.getValue());
            map.put("desc", ve.getDesc());
            list.add(map);
        }
        return JsonViewFactory.create()
            .put("data", list)
            .toJson();
    }

    @RequestMapping(method = RequestMethod.POST, value = "/upload")
    @ResponseBody
    public String upload(@RequestParam("upload") MultipartFile file, Model model) throws Exception{
        if (file.isEmpty()) {
            return JsonViewFactory.create().fail("上传失败，请选择文件").toJson();
        }

        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        File dest = new File(uploadDir + fileName);
        String url = staticPath + fileName;
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            return JsonViewFactory.create().fail(e.getMessage()).toJson();
        }
        return JsonViewFactory.create().put("uploaded", 1).put("fileName", fileName).put("url", url).toJson();
    }

    @RequestMapping(method = RequestMethod.POST, value = "/bupload")
    @ResponseBody
    public String bootstrapUpload(@RequestParam("file_data") MultipartFile file, Model model) throws Exception{
        if (file.isEmpty()) {
            return JsonViewFactory.create().fail("上传失败，请选择文件").toJson();
        }

        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        File dest = new File(uploadDir + fileName);
        String url = staticPath + fileName;
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            return JsonViewFactory.create().fail(e.getMessage()).toJson();
        }
        return JsonViewFactory.create().put("uploaded", 1).put("fileName", fileName).put("url", url).toJson();
    }

    @RequestMapping(method = RequestMethod.POST, value = "/uploads")
    @ResponseBody
    public String uploads(@RequestParam("files") MultipartFile[] files, Model model) throws Exception{
        if (files.length < 1) {
            return JsonViewFactory.create().fail("上传失败，请选择文件").toJson();
        }

        Map<String, String> errors = new HashMap<>();
        Map<String, String> success = new HashMap<>();
        for(MultipartFile file : files) {
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            File dest = new File(uploadDir + fileName);
            String url = staticPath + fileName;
            try {
                file.transferTo(dest);
                success.put(file.getOriginalFilename(), url);
            } catch (IOException e) {
                errors.put(file.getOriginalFilename(), e.getMessage());
            }
        }
        return JsonViewFactory.create().put("uploaded", success.size()).put("errors", errors).put("url", success).toJson();
    }
}
